package com.okbihuo.perm.component.file.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.okbihuo.perm.component.file.domain.ComFile;
import com.okbihuo.perm.component.file.mapper.ComFileMapper;
import com.okbihuo.perm.component.file.service.ComFileService;
import com.okbihuo.perm.core.mp.base.MyServiceImpl;
import com.okbihuo.perm.core.tool.utils.StringUtil;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;

/**
 * 文件接口实现层
 * @author stt
 */
@Service
public class ComFileServiceImpl extends MyServiceImpl<ComFileMapper, ComFile> implements ComFileService {
    @Override
    public ComFile getOneByMd5(String md5) {
        QueryWrapper<ComFile> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("md5", md5);
        return getOne(queryWrapper,false);
    }

    /**
     * 当md5与数据原有一致的，不再新增内容，而是复制原内容数据至新的
     */
    @Override
    public void pointToExist(ComFile newFile, ComFile existFile) {
        newFile.setLocation(existFile.getLocation());
        newFile.setStoreType(existFile.getStoreType());
        newFile.setMd5(existFile.getMd5());
    }

    /**
     * 计算被引用次数
     * @param storeType 相同文件类型才算数
     * @param location 文件地址相同，说明文件内容相同
     * @return 被引用的次数
     */
    @Override
    public int countByFileContent(String storeType, String location) {
        QueryWrapper<ComFile> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("store_type", storeType);
        queryWrapper.eq("location", location);
        return count(queryWrapper);
    }

    @Override
    public boolean updateExpiresAt(Integer id, LocalDateTime time){
        UpdateWrapper<ComFile> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id",id);
        updateWrapper.set(StringUtil.humpToUnderline("expiresAt"),time);
        return update(updateWrapper);
    }
}
